<?php
namespace app\controllers\category;

use fate\http\Request;
use app\models\Posts;
use app\models\User;
use app\models\Category;
use app\libs\Page;
use app\libs\LibUser;

class IndexController extends \fate\web\Controller {
    public function run() {
        $req = Request::getInstance();
        $cateId = $req->getQueryString('id');
        $p = $req->getQueryString('p');

        if(!is_numeric($cateId)) {
            throw new \Exception('category not found');
            exit;
        }
        if(!is_numeric($p)) {
            $p = 1;
        }

        // category
        $cateModel = new Category();
        $cate = $cateModel->getOne('id,pid,name', $cateId);
        if(null === $cate) {
            throw new \Exception('category not found');
            exit;
        }

        $searchCate = '';
        // 父级的话 查找所有子类内容
        if('0' === $cate['pid']) {
            $searchCate = $this->findSubCateIds($cateModel, $cate['id']);
        } else {
            $searchCate = $cate['id'];
        }

        // data
        $pageSize = 20;
        $model = new Posts();
        $where = false === strpos($searchCate, ',')
            ? "status = 1 and cate_id={$searchCate}"
            : "status = 1 and cate_id in({$searchCate})";
        $total = $model->count($where);

        $pageString = (new Page($total, $pageSize))->show();
        $data = $model->getListByPage(
            'id,uid,tags,title,thumb,brief,views,post_time,status',
            $where, $p, $pageSize);

        // user info
        if($data) {
            $user = new User();
            for($i=0,$len=count($data); $i<$len; $i++) {
                $data[$i]['str_uid'] = LibUser::encodeId($data[$i]['uid']);
                $data[$i]['user_info'] = $user->getOne('gender,user_name,avatar', $data[$i]['uid']);
            }
        }

        $this->getView()->enableLayout = true;
        $this->render('@themes/category/index', [
            'nav' => $cate['name'],
            'list' => $data,
            'p' => $p,
            'pageSize' => $pageSize,
            'total' => $total,
            'pageString' => $pageString,
        ]);
    }

    public function findSubCateIds($model, $id) {
        $data = $model->getListByCondition('id', 'pid=' . $id);

        if(!$data) {
            return '';
        }

        $ret = [];
        foreach($data as $v) {
            $ret[] = $v['id'];
        }

        return implode(',', $ret);
    }
}
